package com.hemaapp.hm_FrameWork;

import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.hemaapp.HemaConfig;
import com.hemaapp.hm_FrameWork.cache.HemaImageCache;
import com.hemaapp.hm_FrameWork.image.HemaImageWorker;
import com.hemaapp.hm_FrameWork.net.HemaNetTask;
import com.hemaapp.hm_FrameWork.net.HemaNetWorker;
import com.hemaapp.hm_FrameWork.result.HemaBaseResult;
import com.hemaapp.hm_FrameWork.util.HemaBaseUtil;
import com.hemaapp.hm_FrameWork.util.HemaLogger;
import com.hemaapp.hm_FrameWork.util.HemaToastUtil;
import com.umeng.analytics.MobclickAgent;

/**
 * 基本框架.
 * 特别注意setContentView();应在super.onCreate(savedInstanceState);之前调用否则会导致findView
 * ();等初始化方法失效。 该框架内置了网络访问、图片下载、文件下载功能。
 * <p>
 * 1. 网络访问
 * HemaNetWorker netWorker = {@link #getNetWorker()};
 * netWorker.login();
 * </p>
 * * <p>
 * 2.图片下载使用方法：imageWorker.loadImage(task);
 * </p>
 * <p>
 * 3.集成了log_v(msg)等打印方法以及println(Object)。
 * </p>
 */
public abstract class HemaFragment extends Fragment {

    protected static final String NO_NETWORK = "无网络连接，请检查网络设置。";
    protected static final String FAILED_GETDATA_HTTP = "请求异常。";
    protected static final String FAILED_GETDATA_DATAPARSE = "数据异常。";
    /**
     * 打印TAG，类名
     */
    private String TAG;
    /**
     * 下载图片使用
     */
    private HemaNetWorker netWorker;
    private HemaImageWorker imageWorker;
    /**
     * 获取传参使用
     */
    protected Intent mIntent;
    /**
     * 根view
     */
    protected View rootView;

    /**
     * 根view id
     */
    private int rootViewId;

    private static Fragment currForResultFragment;

    protected HemaFragment() {
        TAG = getLogTag();
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        imageWorker = new HemaImageWorker(getActivity());
        if (rootView == null)
            rootView = LayoutInflater.from(getActivity()).inflate(rootViewId,
                    null, false);
        init();
    }

    @Override
    public void startActivityForResult(Intent intent, int requestCode) {
        if (currForResultFragment == null)
            currForResultFragment = this;
        if (getParentFragment() != null)
            getParentFragment().startActivityForResult(intent, requestCode);
        else
            super.startActivityForResult(intent, requestCode);
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        List<Fragment> fragments = getChildFragmentManager().getFragments();
        if (fragments != null)
            for (Fragment fragment : fragments) {
                fragment.onHiddenChanged(hidden);
            }
        super.onHiddenChanged(hidden);
    }

    @Override
    public void onDestroy() {
        if (netWorker != null)
            netWorker.setOnTaskExecuteListener(null);
        super.onDestroy();
        stopNetThread();// 杀掉网络线程
        if (imageWorker != null)
            imageWorker.clearTasks();// 取消图片下载任务
        recyclePics();// 回收图片
        HemaToastUtil.cancelAllToast();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        return rootView;
    }

    /**
     * 页面初始化
     */
    private void init() {
        findView();
        setListener();
    }

    /**
     * 设置根view
     *
     * @param layoutResID
     */
    public void setContentView(int layoutResID) {
        rootViewId = layoutResID;
    }

    /**
     * 设置根view
     *
     * @param v
     */
    public void setContentView(View v) {
        rootView = v;
    }

    /**
     * 无网络提示
     *
     * @param task
     */
    protected void noNetWork(HemaNetTask task) {
        noNetWork(task.getId());
    }

    /**
     * 无网络提示
     *
     * @param taskID
     */
    protected void noNetWork(int taskID) {
        noNetWork();
    }

    /**
     * 无网络提示
     */
    protected void noNetWork() {
        HemaToastUtil.showLongToast(getActivity(), NO_NETWORK);
    }

    /**
     * 初始化三部曲之：查找控件
     */
    protected abstract void findView();

    /**
     * 初始化三部曲之：设置监听
     */
    protected abstract void setListener();

    /**
     * 暴漏给外部的刷新界面方法
     */
    public void fresh() {

    }

    /**
     * 打印v级别信息
     *
     * @param msg
     */
    protected void log_v(String msg) {
        HemaLogger.v(TAG, msg);
    }

    /**
     * 打印d级别信息
     *
     * @param msg
     */
    protected void log_d(String msg) {
        HemaLogger.d(TAG, msg);
    }

    /**
     * 打印i级别信息
     *
     * @param msg
     */
    protected void log_i(String msg) {
        HemaLogger.i(TAG, msg);
    }

    /**
     * 打印w级别信息
     *
     * @param msg
     */
    protected void log_w(String msg) {
        HemaLogger.w(TAG, msg);
    }

    /**
     * 打印e级别信息
     *
     * @param msg
     */
    protected void log_e(String msg) {
        HemaLogger.e(TAG, msg);
    }

    /**
     * 打印
     *
     * @param msg
     */
    protected void println(Object msg) {
        HemaLogger.println(msg);
    }

    /**
     * 判断字符串是否为空
     *
     * @param str
     * @return true如果该字符串为null或者"",否则false
     */
    protected boolean isNull(String str) {
        return HemaBaseUtil.isNull(str);
    }

    /**
     * 判断网络任务是否都已完成
     *
     * @return
     */
    protected boolean isNetTasksFinished() {
        return netWorker == null || netWorker.isNetTasksFinished();
    }

    // 回收图片
    private void recyclePics() {
        HemaImageCache.get().reMoveCacheInMemByObj(this);
        HemaImageCache.get().recyclePics();
    }

    // 杀掉网络线程
    private void stopNetThread() {
        if (netWorker != null) {
            netWorker.cancelTasks();
        }
    }

    // 获取打印TAG，即类名
    private String getLogTag() {
        return getClass().getSimpleName();
    }

    /**
     * 判断当前是否有可用网络
     *
     * @return 如果有true否则false
     */
    public boolean hasNetWork() {
        ConnectivityManager con = (ConnectivityManager) getActivity()
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = con.getActiveNetworkInfo();// 获取可用的网络服务
        return info != null && info.isAvailable();
    }


    public View findViewById(int id) {
        View view = null;
        if (rootView != null)
            view = rootView.findViewById(id);
        return view;
    }

    /**
     * 显示或更换Fragment
     *
     * @param fragmentClass   Fragment.class
     * @param containerViewId Fragment显示的空间ID
     * @param replace         是否替换
     */
    public void toogleFragment(Class<? extends Fragment> fragmentClass,
                               int containerViewId, boolean replace) {
        FragmentManager manager = getChildFragmentManager();
        String tag = fragmentClass.getName();
        FragmentTransaction transaction = manager.beginTransaction();
        Fragment fragment = manager.findFragmentByTag(tag);

        if (fragment == null) {
            try {
                fragment = fragmentClass.newInstance();
                if (replace)
                    transaction.replace(containerViewId, fragment, tag);
                else
                    // 替换时保留Fragment,以便复用
                    transaction.add(containerViewId, fragment, tag);
            } catch (Exception e) {
                // ignore
            }
        } else {
            // nothing
        }
        // 遍历存在的Fragment,隐藏其他Fragment
        List<Fragment> fragments = manager.getFragments();
        if (fragments != null)
            for (Fragment fm : fragments)
                if (!fm.equals(fragment))
                    transaction.hide(fm);

        transaction.show(fragment);
        transaction.commit();
    }

    public void showProgressDialog(String text) {
        HemaFragmentActivity activity = (HemaFragmentActivity) getActivity();
        activity.showProgressDialog(text);
    }

    public void showProgressDialog(int text) {
        HemaFragmentActivity activity = (HemaFragmentActivity) getActivity();
        activity.showProgressDialog(text);
    }

    public void cancelProgressDialog() {
        HemaFragmentActivity activity = (HemaFragmentActivity) getActivity();
        activity.cancelProgressDialog();
    }

    public void showTextDialog(String text) {
        HemaFragmentActivity activity = (HemaFragmentActivity) getActivity();
        activity.showTextDialog(text);
    }

    public void showTextDialog(int text) {
        HemaFragmentActivity activity = (HemaFragmentActivity) getActivity();
        activity.showTextDialog(text);
    }

    public void cancelTextDialog() {
        HemaFragmentActivity activity = (HemaFragmentActivity) getActivity();
        activity.cancelTextDialog();
    }


    /**
     * 获取网络请求工具类
     */
    public HemaNetWorker getNetWorker() {
        if (netWorker == null) {
            netWorker = initNetWorker();
            netWorker.setOnTaskExecuteListener(new NetTaskExecuteListener(
                    getActivity()));
        }
        return netWorker;
    }

    /**
     * 初始化NetWorker
     */
    protected abstract HemaNetWorker initNetWorker();

    /**
     * 返回数据前的操作，如显示进度条
     *
     * @param netTask
     */
    protected abstract void callBeforeDataBack(HemaNetTask netTask);

    /**
     * 返回数据后的操作，如关闭进度条
     *
     * @param netTask
     */
    protected abstract void callAfterDataBack(HemaNetTask netTask);

    /**
     * 服务器处理成功
     *
     * @param netTask
     * @param baseResult
     */
    protected abstract void callBackForServerSuccess(HemaNetTask netTask,
                                                     HemaBaseResult baseResult);

    /**
     * 服务器处理失败
     *
     * @param netTask
     * @param baseResult
     */
    protected abstract void callBackForServerFailed(HemaNetTask netTask,
                                                    HemaBaseResult baseResult);

    /**
     * 获取数据失败
     *
     * @param netTask
     * @param failedType 失败原因
     *                   <p>
     *                   See {@link HemaNetWorker#FAILED_DATAPARSE
     *                   HemaNetWorker.FAILED_DATAPARSE},
     *                   {@link HemaNetWorker#FAILED_HTTP HemaNetWorker.FAILED_HTTP},
     *                   {@link HemaNetWorker#FAILED_NONETWORK
     *                   HemaNetWorker.FAILED_HTTP}
     *                   </p>
     */
    protected abstract void callBackForGetDataFailed(HemaNetTask netTask,
                                                     int failedType);

    /**
     * 自动登录失败
     *
     * @param netWorker
     * @param netTask
     * @param failedType 如果failedType为0表示服务器处理失败,其余参照
     *                   {@link HemaNetWorker#FAILED_DATAPARSE
     *                   HemaNetWorker.FAILED_DATAPARSE},
     *                   {@link HemaNetWorker#FAILED_HTTP HemaNetWorker.FAILED_HTTP},
     *                   {@link HemaNetWorker#FAILED_NONETWORK
     *                   HemaNetWorker.FAILED_NONETWORK}
     * @param baseResult 执行结果(仅当failedType为0时有值,其余为null)
     * @return true表示拦截该任务执行流程,
     * 不会继续调用callBackForServerFailed或者callBackForGetDataFailed方法;
     * false反之
     */
    public abstract boolean onAutoLoginFailed(HemaNetWorker netWorker,
                                              HemaNetTask netTask, int failedType, HemaBaseResult baseResult);


    private class NetTaskExecuteListener extends HemaNetTaskExecuteListener {

        public NetTaskExecuteListener(Context context) {
            super(context);
        }

        @Override
        public void onPreExecute(HemaNetWorker netWorker, HemaNetTask netTask) {
            callBeforeDataBack(netTask);
        }

        @Override
        public void onPostExecute(HemaNetWorker netWorker, HemaNetTask netTask) {
            callAfterDataBack(netTask);
        }

        @Override
        public void onServerSuccess(HemaNetWorker netWorker,
                                    HemaNetTask netTask, HemaBaseResult baseResult) {
            callBackForServerSuccess(netTask, baseResult);
        }

        @Override
        public void onServerFailed(HemaNetWorker netWorker,
                                   HemaNetTask netTask, HemaBaseResult baseResult) {
            callBackForServerFailed(netTask, baseResult);
        }

        @Override
        public void onExecuteFailed(HemaNetWorker netWorker, HemaNetTask netTask, int failedType) {
            callBackForGetDataFailed(netTask, failedType);
        }

        @Override
        public boolean onAutoLoginFailed(HemaNetWorker netWorker,
                                         HemaNetTask netTask, int failedType, HemaBaseResult baseResult) {
            return HemaFragment.this.onAutoLoginFailed(netWorker, netTask,
                    failedType, baseResult);
        }
    }

    // 友盟相关
    @Override
    public void onResume() {
        super.onResume();
        if (HemaConfig.UMENG_ENABLE)
            MobclickAgent.onPageStart(getClass().getSimpleName());
    }

    @Override
    public void onPause() {
        super.onPause();
        if (HemaConfig.UMENG_ENABLE)
            MobclickAgent.onPageEnd(getClass().getSimpleName());
    }
    // 友盟相关end
}
